package com.typhoon.spring_shiro.controller.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by hujun on 2017/2/16.
 * 登录校验
 */
public class AccessControlInterceptor implements HandlerInterceptor {
//    @Resource
//    private LoginService loginService;
//
//    @Resource
//    private WorkerService workerService;

    private static final Logger LOG = LoggerFactory.getLogger(AccessControlInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        Method method = handlerMethod.getMethod();
        //String redirectUrl = httpServletRequest.getParameter("redirectUrl");//需要跳转的地址
        String sid = httpServletRequest.getParameter("sid");
//        RequireLogin requireLogin = method.getAnnotation(RequireLogin.class);
//        if (requireLogin == null) {
//            Class<?> cls = handlerMethod.getBeanType();
//            requireLogin = cls.getAnnotation(RequireLogin.class);
//        }
//        //如果是ip受限，则跳转到错误页面
//        if(!loginService.isAllowedIP(HycCommonUtils.getRealRemoteIp(httpServletRequest))){
//            /*String url = httpServletRequest.getRequestURI();
//            LOG.debug("loginUserInfo.loginUserId", url);
//            //TODO:
//            String loginUrl = SessionConstant.DOMAIN + "?redirectUrl=" + redirectUrl;
//            httpServletResponse.sendRedirect(loginUrl);*/
//            putParamResult(httpServletResponse,PResult.IP_LIMIT);
//            return false;
//        }
//        if (requireLogin != null && !requireLogin.value()) {
//            return true;
//        }else{
//            if(sid == null){//必要要有sid
//               /* String url = httpServletRequest.getRequestURI();
//                LOG.debug("loginUserInfo.loginUserId", url);
//                //TODO:
//                String loginUrl = SessionConstant.DOMAIN + "?redirectUrl=" + redirectUrl;
//                httpServletResponse.sendRedirect(loginUrl);*/
//                sid = CookieUtils.getCookie(httpServletRequest, SessionConstant.SESSION_KEY);
//                if(sid == null) {
//                    putParamResult(httpServletResponse, PResult.ILLEGA_ACCESS_ERROR);
//                    return false;
//                }
//            }

            boolean isLogin = false;
//            try {
//                isLogin = loginService.isLogin(sid);
//            }catch (Exception e){
//                LOG.error("rpc service call fail",e);
//            }
            if(!isLogin){
                /*String url = httpServletRequest.getRequestURI();
                LOG.debug("loginUserInfo.loginUserId", url);
                String loginUrl = SessionConstant.DOMAIN + "?redirectUrl=" + redirectUrl;
                httpServletResponse.sendRedirect(loginUrl);*/
               // putParamResult(httpServletResponse,PResult.ILLEGA_ACCESS_ERROR);
                return false;
            }
            Object bean = handlerMethod.getBean();
//            if(bean instanceof CurrentWorkerAware){
//                String decodeSid = Encrypt.decrypt(sid);
//                LOG.info("decodeSid=" + decodeSid);
//                int workerId = HycCommonUtils.evalInt(decodeSid.substring(decodeSid.indexOf("|") + 1, decodeSid.lastIndexOf("|")));
//                try {
//                    Worker worker = workerService.select(workerId);
//                    ((CurrentWorkerAware) bean).setCurrentWorker(worker);
//                }catch (Exception e){
//                    LOG.warn("get workerInfo error|workerId=" + workerId,e.getMessage());
//                }
//            }
            return true;
        }
 //   }

//    private void putParamResult(HttpServletResponse response, PResult result) {
//        HashMap results = new HashMap();
//        results.put("code", Integer.valueOf(result.getCode()));
//        results.put("msg", result.getMessage());
//        ResponseUtils.renderJson(response, JSON.toJSONString(results));
//    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
